# coding: utf-8
from PySide6.QtCore import Qt
from PySide6.QtGui import QResizeEvent, QColor
from PySide6.QtWidgets import QApplication, QWidget
from qfluentwidgets import NavigationItemPosition, FluentIcon as FIF, MSFluentWindow

from common import APP_NAME, Icon, cfg, signalBus, openUrl, FEEDBACK_URL
from components import CentreImageLabel
from .batch_interface import BatchInterface
from .conversion_interface import ConversionInterface
from .history_interface import HistoryInterface
from .setting_interface import SettingInterface
from .voices_interface import VoicesInterface


class MainWindow(MSFluentWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.conversionInterface = ConversionInterface(self)
        self.historyInterface = HistoryInterface(self)
        self.batchInterface = BatchInterface(self)
        self.voicesInterface = VoicesInterface(self)
        self.settingInterface = SettingInterface(self)

        self.wallpaperLabel = CentreImageLabel(self)

        self.__initWindow()
        self.__initSubInterface()
        self.__connectSignals()
        self.__initWallpaper()

    def __initWindow(self):
        self.setMinimumSize(1000, 600)
        self.setWindowTitle(APP_NAME)
        self.setWindowIcon(Icon.LOGO.icon())
        self.setMicaEffectEnabled(cfg.get(cfg.micaEnabled))

        desktop = QApplication.primaryScreen().availableGeometry()
        w, h = desktop.width(), desktop.height()
        self.move(w // 2 - self.width() // 2, h // 2 - self.height() // 2)
        self.show()

    def __initSubInterface(self):
        self.addSubInterface(self.conversionInterface, Icon.Conversion, '转换', isTransparent=True)
        self.addSubInterface(self.historyInterface, FIF.HISTORY, '历史', isTransparent=True)
        self.addSubInterface(self.batchInterface, FIF.MENU, '批量', isTransparent=False)
        position = NavigationItemPosition.BOTTOM
        self.addSubInterface(self.voicesInterface, FIF.BOOK_SHELF, '声音库', position=position, isTransparent=True)
        self.addSubInterface(self.settingInterface, FIF.SETTING, '设置', position=position, isTransparent=True)

    def __connectSignals(self):
        cfg.themeChanged.connect(lambda: self.setWindowIcon(Icon.LOGO.icon()))
        signalBus.switchToSample.connect(self.switchToSample)
        signalBus.wallpaperEnabledChanged.connect(self.setEnabledWallpaper)
        signalBus.wallpaperChanged.connect(self.setWallpaper)
        signalBus.wallpaperOpacityChanged.connect(self.setWallpaperMaskOpacity)
        signalBus.wallpaperLightColorChanged.connect(self.setWallpaperMaskLightColor)
        signalBus.wallpaperDarkColorChanged.connect(self.setWallpaperMaskDarkColor)

        signalBus.appErrorSignal.connect(self.onAppError)

    def __initWallpaper(self):
        self.setWallpaper(cfg.get(cfg.wallpaperImage))
        self.wallpaperLabel.setEnableMask(True)
        self.wallpaperLabel.lower()
        self.setEnabledWallpaper(cfg.get(cfg.wallpaperEnabled))
        self.setWallpaperMaskOpacity(cfg.get(cfg.wallpaperOpacity))
        self.setWallpaperMaskLightColor(cfg.get(cfg.wallpaperLightColor))
        self.setWallpaperMaskDarkColor(cfg.get(cfg.wallpaperDarkColor))

    def switchTo(self, interface: QWidget):
        super().switchTo(interface)

    def switchToSample(self, interfaceName, data: dict):
        """ 切换到样本 """
        w = getattr(self, interfaceName)
        if w in [self.conversionInterface, self.batchInterface]:
            w.setLanguage(**data)
        print(f"切换到 {w} 界面，数据: {data}")
        self.stackedWidget.setCurrentWidget(w, False)

    def resizeEvent(self, event: QResizeEvent):
        self.wallpaperLabel.resize(event.size())
        super().resizeEvent(event)

    def setEnabledWallpaper(self, enable: bool):
        self.wallpaperLabel.setVisible(enable)

    def setWallpaper(self, fileName: str = None):
        self.wallpaperLabel.setImage(fileName)

    def setWallpaperMaskOpacity(self, opacity: int):
        self.wallpaperLabel.setMaskOpacity(opacity)

    def setWallpaperMaskLightColor(self, light_color: QColor):
        self.wallpaperLabel.setMaskLightColor(light_color)

    def setWallpaperMaskDarkColor(self, dark_color: QColor):
        self.wallpaperLabel.setMaskDarkColor(dark_color)

    def onAppError(self, message: str):
        """ app error slot """
        QApplication.clipboard().setText(message)
        self.showMessageBox(
            self.tr("发生未处理的异常"),
            self.tr("错误信息已写入粘贴板和日志。你要报告吗？"),
            True,
            lambda: openUrl(FEEDBACK_URL)
        )

    def updateFrameless(self):
        stayOnTop = Qt.WindowStaysOnTopHint if self.windowFlags() & Qt.WindowStaysOnTopHint else 0
        self.setWindowFlags(Qt.FramelessWindowHint | stayOnTop)

        self.windowEffect.enableBlurBehindWindow(self.winId())
        self.windowEffect.addWindowAnimation(self.winId())

        self.windowEffect.setAcrylicEffect(self.winId())
